//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.springboot.cloud.common.core.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.GsonBuilder;
import com.lly835.bestpay.config.AliPayConfig;
import com.lly835.bestpay.config.SignType;
import com.lly835.bestpay.enums.AlipayTradeStatusEnum;
import com.lly835.bestpay.enums.BestPayPlatformEnum;
import com.lly835.bestpay.model.DownloadBillRequest;
import com.lly835.bestpay.model.OrderQueryRequest;
import com.lly835.bestpay.model.OrderQueryResponse;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.model.alipay.AliPayApi;
import com.lly835.bestpay.model.alipay.request.AliPayOrderQueryRequest;
import com.lly835.bestpay.model.alipay.request.AliPayPcRequest;
import com.lly835.bestpay.model.alipay.request.AliPayOrderQueryRequest.BizContent;
import com.lly835.bestpay.model.alipay.response.AliPayAsyncResponse;
import com.lly835.bestpay.model.alipay.response.AliPayOrderQueryResponse;
import com.lly835.bestpay.model.alipay.response.AliPayOrderQueryResponse.AlipayTradeQueryResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.lly835.bestpay.service.impl.alipay.AliPayServiceImpl;
import com.lly835.bestpay.service.impl.alipay.AliPaySignature;
import com.lly835.bestpay.utils.JsonUtil;
import com.lly835.bestpay.utils.MapUtil;
import com.lly835.bestpay.utils.WebUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.Retrofit.Builder;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author qjmove
 */
public class AliAppPayService {
    private static final Logger log = LoggerFactory.getLogger(AliPayServiceImpl.class);
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private AliPayConfig aliPayConfig;
    private Retrofit retrofit;

    public AliAppPayService() {
        this.retrofit = (new Builder()).baseUrl("https://openapi.alipay.com/").addConverterFactory(GsonConverterFactory.create((new GsonBuilder()).setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create())).client((new okhttp3.OkHttpClient.Builder()).addInterceptor((new HttpLoggingInterceptor()).setLevel(Level.BODY)).build()).build();
    }

    public void setAliPayConfig(AliPayConfig aliPayConfig) {
        this.aliPayConfig = aliPayConfig;
    }

    public AlipayTradeAppPayResponse pay(PayRequest request) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", this.aliPayConfig.getAppId(), this.aliPayConfig.getPrivateKey(), "json", "utf8", this.aliPayConfig.getAliPayPublicKey(), "RSA2");
        AlipayTradeAppPayRequest payRequest = new AlipayTradeAppPayRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(request.getOrderId());
        model.setTotalAmount(request.getOrderAmount().toString());
        model.setSubject("钱包充值");
        model.setTimeoutExpress("90m");
        payRequest.setBizModel(model);
        payRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());

        AlipayTradeAppPayResponse response = null;
        try {
            response = alipayClient.sdkExecute(payRequest);

            log.info("支付宝下单信息：" + response.getBody());
            if (response.isSuccess()) {
                log.info("支付宝下单成功：{}" + response.getBody());
                return response;
            } else {
                log.info("支付宝下单失败：返回码-" + response.getCode() + "错误信息-" + response.getMsg());
            }
        } catch (AlipayApiException e) {
            log.info("支付宝下单失败：{}", e.getStackTrace());
            e.printStackTrace();
        }
        return response;
    }

    public boolean verify(Map<String, String> toBeVerifiedParamMap, SignType signType, String sign) {
        return AliPaySignature.verify(toBeVerifiedParamMap, this.aliPayConfig.getAliPayPublicKey());
    }

    public PayResponse asyncNotify(String notifyData) {
        try {
            notifyData = URLDecoder.decode(notifyData, "UTF-8");
        } catch (UnsupportedEncodingException var5) {
            var5.printStackTrace();
        }

        if (!AliPaySignature.verify(MapUtil.form2Map(notifyData), this.aliPayConfig.getAliPayPublicKey())) {
            log.error("【支付宝支付异步通知】签名验证失败, response={}", notifyData);
            throw new RuntimeException("【支付宝支付异步通知】签名验证失败");
        } else {
            HashMap<String, String> params = MapUtil.form2MapWithCamelCase(notifyData);
            AliPayAsyncResponse response = (AliPayAsyncResponse) MapUtil.mapToObject(params, AliPayAsyncResponse.class);
            String tradeStatus = response.getTradeStatus();
            if (!tradeStatus.equals("TRADE_FINISHED") && !tradeStatus.equals("TRADE_SUCCESS")) {
                throw new RuntimeException("【支付宝支付异步通知】发起支付, trade_status != SUCCESS | FINISHED");
            } else {
                return this.buildPayResponse(response);
            }
        }
    }

    public OrderQueryResponse query(OrderQueryRequest request) {
        AliPayOrderQueryRequest aliPayOrderQueryRequest = new AliPayOrderQueryRequest();
        aliPayOrderQueryRequest.setAppId(this.aliPayConfig.getAppId());
        aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter));
        BizContent bizContent = new BizContent();
        bizContent.setOutTradeNo(request.getOrderId());
        bizContent.setTradeNo(request.getOutOrderId());
        aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", ""));
        aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), this.aliPayConfig.getPrivateKey()));
        Call<AliPayOrderQueryResponse> call = ((AliPayApi) this.retrofit.create(AliPayApi.class)).orderQuery(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest));
        Response retrofitResponse = null;

        try {
            retrofitResponse = call.execute();
        } catch (IOException var7) {
            var7.printStackTrace();
        }

        assert retrofitResponse != null;

        if (!retrofitResponse.isSuccessful()) {
            throw new RuntimeException("【查询支付宝订单】网络异常");
        } else {
            assert retrofitResponse.body() != null;

            AlipayTradeQueryResponse response = ((AliPayOrderQueryResponse) retrofitResponse.body()).getAlipayTradeQueryResponse();
            if (!response.getCode().equals("10000")) {
                throw new RuntimeException("【查询支付宝订单】code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg()));
            } else {
                return OrderQueryResponse.builder().orderStatusEnum(AlipayTradeStatusEnum.findByName(response.getTradeStatus()).getOrderStatusEnum()).outTradeNo(response.getTradeNo()).orderId(response.getOutTradeNo()).resultMsg(response.getMsg()).finishTime(response.getSendPayDate()).build();
            }
        }
    }


    private PayResponse buildPayResponse(AliPayAsyncResponse response) {
        PayResponse payResponse = new PayResponse();
        payResponse.setPayPlatformEnum(BestPayPlatformEnum.ALIPAY);
        payResponse.setOrderAmount(Double.valueOf(response.getTotalAmount()));
        payResponse.setOrderId(response.getOutTradeNo());
        payResponse.setOutTradeNo(response.getTradeNo());
        return payResponse;
    }
}
